import { NestApplication, NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { HttpExceptionFilter } from './core/filter/http-exception/http-exception.filter'
import { TransformInterceptor } from './core/interceptor/transform/transform.interceptor'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { ValidationPipe } from '@nestjs/common'
// import * as cookieParser from 'cookie-parser'
import { getPublicIp } from 'utils/index'

async function bootstrap() {
  console.log('当前环境:', process.env.NODE_ENV, '数据库主机:', process.env.DB_HOST, '端口:', process.env.DB_PORT)
  console.log('当前最新公网IP:', await getPublicIp())
  const isProduction = process.env.NODE_ENV === 'production'
  const app = await NestFactory.create<NestApplication>(AppModule, {
    rawBody: true // 获取原始请求体 用于签名验证
  })
  // 设置全局路由前缀
  app.setGlobalPrefix('api/nest')
  // 过滤器
  app.useGlobalFilters(new HttpExceptionFilter())
  // 拦截器
  app.useGlobalInterceptors(new TransformInterceptor())
  // 配置swagger
  const config = new DocumentBuilder()
    .setTitle('OnlineJHCatering api document')
    .setDescription('味巷食铺点餐的接口文档，接口地址: https://tears.asia:3000/docs')
    .setVersion('1.0')
    .addBearerAuth({
      type: 'http', // 认证类型
      scheme: 'bearer', // 认证方案
      bearerFormat: 'JWT', // 认证格式
      name: 'Authorization',
      in: 'header', // 认证位置
      description: '请输入token，无需Bearer前缀',
    }, 'JWT') // 开启BearerAuth认证
    .build() // 创建文档对象

  const document = SwaggerModule.createDocument(app, config) // 创建文档
  const customCss = `
    .swagger-ui input[type="text"],
    .swagger-ui input[type="number"],
    .swagger-ui select {
      min-width: 100px;
      background: #fff;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      margin: 5px ;
      font-size: 14px;
      padding: 9px 10px;
    }

    .swagger-ui .parameter__empty_value_toggle {
      display: none !important;
    }
  `
  SwaggerModule.setup('docs', app, document, {
    customCss,
    swaggerOptions: {
      defaultModelRendering: 'form', // 折叠所有模型
      persistAuthorization: true, // 保持认证状态
    },
  }) // 配置文档路径

  // 全局cookie中间件
  // app.use(cookieParser())
  app.enableCors({
    origin: isProduction ? ['https://tears.asia', 'https://www.tears.asia', 'http://8.138.47.207', 'https://orderfood.tears.asia'] : true,  // true 允许所有域名访问
    // credentials: true, // 允许携带cookie
    methods: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    // exposedHeaders: ['Cookie'],
    maxAge: 86400
  })

  // 管道
  app.useGlobalPipes(new ValidationPipe())
  await app.listen(process.env.PORT ?? 3001)
}
bootstrap()
